package com.joker.demo;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
import java.io.File;
import java.io.IOException;

public class AudioRecorder {

    // 设置录音的格式
    private static final AudioFormat FORMAT = new AudioFormat(
            AudioFormat.Encoding.PCM_SIGNED, // 编码格式
            16000, // 采样率
            16, // 量化位数
            1, // 声道数
            2, // 每个样本的字节数
            16000, // 每秒的采样数
            true // 是否是大端序
    );

    public static void main(String[] args) {
        File audioFile = new File("recorded.wav");
        try {
            // 创建并启动录音线程
            AudioInputStream audioInputStream = getAudioInput();
            // 将录音数据写入文件
            AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, audioFile);
            System.out.println("录音完成，文件保存为: " + audioFile.getAbsolutePath());
        } catch (IOException | LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    // 录制音频的方法
    private static AudioInputStream getAudioInput() throws LineUnavailableException {
        // 获取音频线（即音频输入源）
        TargetDataLine line = AudioSystem.getTargetDataLine(FORMAT);
        line.open(FORMAT);
        line.start();

        // 创建录音的缓冲区和音频输入流
        byte[] buffer = new byte[4096];
        AudioInputStream audioInputStream = new AudioInputStream(line);

        // 启动录音线程
        Thread recordingThread = new Thread(() -> {
            try {
                System.out.println("开始录音...");
                while (true) {
                    int bytesRead = line.read(buffer, 0, buffer.length);
                    if (bytesRead == -1) break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                line.stop();
                line.close();
            }
        });
        recordingThread.start();
        System.out.println("录音中...");
        // 录音持续时间
        try {
            Thread.sleep(5000); // 录制5秒
            System.out.println("录音结束...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return audioInputStream;
    }
}